package com.neusoft.neuiotms.dcvm.controller;

import java.util.List;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.HandlerMapping;

import com.neusoft.neuiotms.dcvm.model.Mock;
import com.neusoft.neuiotms.dcvm.repository.MockRepository;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Api("模拟接口")
@RestController
@RequestMapping(value = "/mock")
public class MockController {

    @Autowired
    private MockRepository mockRepository;

    @ApiOperation("模拟接口")
    @RequestMapping("/**")
    public String mock(HttpServletRequest request) {
        final String apiUrl = this.extractPathFromPattern(request);
        if (MockController.log.isDebugEnabled()) {
            MockController.log.debug(apiUrl);
        }

        final Mock mock = this.mockRepository.findOneByApi(apiUrl);
        if (null == mock) {
            final List<Mock> all = this.mockRepository.findAll();
            final String[] apiSegments = apiUrl.split("/");
            final List<Mock> possibles = all.stream().filter(it -> {
                final String[] segments = it.getApi().split("/");
                if (apiSegments.length != segments.length) {
                    return false;
                }
                return true;
            }).collect(Collectors.toList());

            if (possibles.size() > 0) {
                possibles.sort((o1, o2) -> {
                    final String[] o1Segments = o1.getApi().split("/");
                    int o1MatchedCount = 0;
                    for (int i = 0; i < apiSegments.length; i++) {
                        if (apiSegments[i].equals(o1Segments[i])) {
                            o1MatchedCount++;
                        }
                    }

                    final String[] o2Segments = o2.getApi().split("/");
                    int o2MatchedCount = 0;
                    for (int i = 0; i < apiSegments.length; i++) {
                        if (apiSegments[i].equals(o2Segments[i])) {
                            o2MatchedCount++;
                        }
                    }

                    return o2MatchedCount - o1MatchedCount;
                });

                return possibles.get(0).getData();
            }

            return "{}";
        }
        return mock.getData();
    }

    /**
     * 获取额外参数
     *
     * @param request
     * @return
     */
    private String extractPathFromPattern(final HttpServletRequest request) {
        final String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
        final String bestMatchPattern = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
        return new AntPathMatcher().extractPathWithinPattern(bestMatchPattern, path);
    }
}
